package com.shensi.appCollect.controller;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.shensi.api.admin.domian.station.ClassSettlement;
import com.shensi.api.admin.domian.station.ClassSettlementOilmachine;
import com.shensi.appCollect.anno.SimpleRepeatedReqLimit;
import com.shensi.appCollect.dao.StationMapper;
import com.shensi.appCollect.enums.CardRecordType;
import com.shensi.appCollect.enums.PayTypeEnum;
import com.shensi.appCollect.pojo.*;
import com.shensi.appCollect.pojo.dto.CardClassSettDto;
import com.shensi.appCollect.rocketmq.MyConsumerService;
import com.shensi.appCollect.service.ClassSettlementCardService;
import com.shensi.appCollect.service.ClassSettlementService;
import com.shensi.appCollect.service.EnterpriseService;
import com.shensi.appCollect.service.PayOrderService;
import com.shensi.appCollect.service.PosMachineService;
import com.shensi.appCollect.utils.CodeMsg;
import com.shensi.appCollect.utils.MathUtil;
import com.shensi.appCollect.utils.ResultData;
import com.shensi.appCollect.utils.exception.CustomException;
import com.shensi.appCollect.utils.tonglianpay.tlfusclasspay.TLFusClassPayUtil;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.common.message.MessageExt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 班结Controller
 *
 * @author qujia
 * @date 2021-11-27
 */

@RestController
@Api(tags = "新版本POS班结")
//@QuJiaRequest()
@CrossOrigin
public class ClassSettlementController {
    private static Logger logger = (Logger) LoggerFactory.getLogger(ClassSettlementController.class);
    @Resource
    private ClassSettlementService classSettlementService;
    @Resource
    private PosMachineService posMachineService;
    @Resource
    private PayOrderService payOrderService;
    @Resource
    private EnterpriseService enterpriseService;
    @Resource
    private MyConsumerService myConsumerService;
    @Resource
    private ClassSettlementCardService classSettlementCardService;
    @Resource
    private StationMapper stationMapper;

    @Value("${qujia.bgBaseUrl}")
    private String bgBaseUrl;

    @Autowired
    private RestTemplate restTemplate;




    /**
     * 查询未班结列表
     */

    @GetMapping(value = "/inittest")
    public void inittest() {
        MessageExt a = new MessageExt();
        myConsumerService.onMessage(a);
    }




    /**
     * 查询未班结列表
     */
    @ApiOperation(value = "询未班结列表", httpMethod = "POST", notes = "询未班结列表")
    @PostMapping(value = "/initiateClassSe", produces = "application/json;charset=UTF-8")
    @Transactional
    public String initiateClassSe(@RequestBody ClassSettlement classSettlement) {
        ResultData resultData = null;
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        if (classSettlement.getVersion() == null || Integer.valueOf(classSettlement.getVersion()) < 1) {
            resultData = ResultData.error(CodeMsg.ERROR_VERSION_INFO);
            return gson.toJson(resultData);
        }

        Map<String, Object> resultMap = new HashMap<String, Object>();
        if (classSettlement.getStationId() == null || classSettlement.getEquipmentCode() == null) {
            resultData = ResultData.error(CodeMsg.REQUEST_FAIL);
            return gson.toJson(resultData);
        }
        String userLevel = "1";
//        if (classSettlement.getUserId() == null ) {
//            Station station =  stationMapper.selectStationById(classSettlement.getStationId().intValue());
//            if(station.getOpenStaffClass() == 1) {
//                resultData = ResultData.error(CodeMsg.NOT_BANSHUANG);
//                return gson.toJson(resultData);
//            }
//        }else{
        if(classSettlement.getUserId()!=null){
            userLevel = classSettlementService.isStaffBGApi(classSettlement.getUserId());
        }
//        userLevel = 1原来的 2员工的 3员工关闭 报错 4 油站且开启 也就是去除所有员工的
        if(userLevel.equals("3")){
            resultData = ResultData.error(CodeMsg.NOT_OPEN_FAIL);
            return gson.toJson(resultData);
        }
        if(userLevel.equals("2")){
            classSettlement.setOpenStaffClass(1);
            classSettlement.setOilPersonnelId(classSettlement.getUserId().toString());
        }
        if(userLevel.equals("4")){
            classSettlement.setOpenStaffClass(1);
        }


        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currentTime = fmt.format(new Date());
        String startTime = null;
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("stationId", classSettlement.getStationId());
        Map<String, Object> endTimeMap =new HashMap<String, Object>();

        if(userLevel.equals("2")){
            params.put("oilPersonnelId", classSettlement.getOilPersonnelId());
            endTimeMap = classSettlementService.queryLastEndTimeStaff(params);
        }else{
            endTimeMap  = classSettlementService.queryLastEndTime(params);
        }



        params.clear();
        params.put("serviceType", "POS");//pos机调用，group by只根据油品区分
        if (endTimeMap != null && endTimeMap.containsKey("classEndTime") && endTimeMap.get("classEndTime") != null) {
//            params.put("createStartTime","2021-07-10 00:00:00");
            startTime = endTimeMap.get("classEndTime").toString();
        }
        params.put("createStartTime", startTime);
        params.put("createEndTime", currentTime);
        params.put("stationId", classSettlement.getStationId());
        if(userLevel.equals("2")){
            params.put("oilPersonnelId", classSettlement.getOilPersonnelId());
        }else if(userLevel.equals("4")){
            params.put("openStaffClassInStation", 1);
        }
        List<ClassSettlement> classSettlements = classSettlementService.queryUntreatedData(params);
//        List<ClassSettlementCard> classSettlementCards = classSettlementCardService.queryUntreatedDataSum(params);
//
//        for (ClassSettlementCard classSettlementCard : classSettlementCards) {
//
//        }
        Map<String, Object> summaryMap = new HashMap<String, Object>();
        Long orderCount = 0L;//订单笔数
        BigDecimal amt = BigDecimal.ZERO;//实收金额
        BigDecimal receivableAmt = BigDecimal.ZERO;//应收金额
        BigDecimal discountAmt = BigDecimal.ZERO;//优惠金额
        BigDecimal orderLiters = BigDecimal.ZERO;//加油升数
        BigDecimal moreAmt = BigDecimal.ZERO;//短款金额
        BigDecimal refundAmt = BigDecimal.ZERO;//退款金额
        for (ClassSettlement settlement : classSettlements) {
            System.out.println(settlement.toString());
            orderCount = orderCount + settlement.getOrderCount();
            amt = amt.add(settlement.getAmt());
            receivableAmt = receivableAmt.add(settlement.getReceivableAmt());
            discountAmt = discountAmt.add(settlement.getDiscountAmt());
            orderLiters = orderLiters.add(settlement.getOrderLiters() != null ? settlement.getOrderLiters() : BigDecimal.ZERO);
            moreAmt = moreAmt.add(settlement.getMoreAmt());
            refundAmt = refundAmt.add(settlement.getRefundAmt());
        }
        summaryMap.put("orderCount", orderCount);
        summaryMap.put("amt", amt);
        summaryMap.put("receivableAmt", receivableAmt);
        summaryMap.put("discountAmt", discountAmt);
        summaryMap.put("orderLiters", orderLiters);
        summaryMap.put("moreAmt", moreAmt);
        summaryMap.put("returnAmt", refundAmt);
        params.put("serviceType", "POS4USER");
        List<ClassSettlement> classSettlementsByUser = classSettlementService.queryUntreatedData(params);
        String userName = "";
        orderLiters = BigDecimal.ZERO;
        refundAmt = BigDecimal.ZERO;
        amt = BigDecimal.ZERO;
        orderCount = 0L;
        List<ClassSettlement> detailList = new ArrayList<ClassSettlement>();
        List<Map<String, Object>> userDetail = new ArrayList<Map<String, Object>>();
        for (ClassSettlement settlement : classSettlementsByUser) {
            if (!settlement.getOilPersonnelName().equals(userName)) {
                if (!userName.equals("")) {
                    Map<String, Object> map = new HashMap<String, Object>();

                    ClassSettlement hz = new ClassSettlement();
                    hz.setOilName("合计");
                    hz.setOrderCount(orderCount);
                    hz.setAmt(amt);
                    hz.setOrderLiters(orderLiters);
                    hz.setRefundAmt(refundAmt);
                    detailList.add(hz);
                    map.put("userName", userName);
                    map.put("detailList", detailList);
                    userDetail.add(map);
                }
                userName = settlement.getOilPersonnelName();
                //新的加油员，
                detailList = new ArrayList<ClassSettlement>();
                orderLiters = BigDecimal.ZERO;
                refundAmt = BigDecimal.ZERO;
                amt = BigDecimal.ZERO;
                orderCount = 0L;
            }
            amt = amt.add(settlement.getAmt());
            orderLiters = orderLiters.add(settlement.getOrderLiters() != null ? settlement.getOrderLiters() : BigDecimal.ZERO);
            refundAmt = refundAmt.add(settlement.getRefundAmt());
            orderCount = orderCount + settlement.getOrderCount();
            detailList.add(settlement);
        }
        Map<String, Object> map = new HashMap<String, Object>();
        ClassSettlement hz = new ClassSettlement();
        hz.setOilName("合计");
        hz.setOrderCount(orderCount);
        hz.setAmt(amt);
        hz.setOrderLiters(orderLiters);
        hz.setRefundAmt(refundAmt);
        detailList.add(hz);
        map.put("userName", userName);
        map.put("detailList", detailList);
        userDetail.add(map);

        resultMap.put("summary", summaryMap);
        resultMap.put("details", classSettlements);
//        resultMap.put("classSettlementCards",classSettlementCards);
        resultMap.put("details4User", userDetail);
        resultMap.put("currentTime", currentTime);
        resultData = ResultData.success(resultMap);
        return gson.toJson(resultData);
    }

    /**
     * POS查询班结列表或者详情
     */
    @ApiOperation(value = "POS查询班结列表或者详情", httpMethod = "POST", notes = "POS查询班结列表或者详情")
    @PostMapping(value = "/list4pos", produces = "application/json;charset=UTF-8")
    @Transactional
    public String list4pos(@RequestBody ClassSettlement classSettlement) {
        String  userLevel = "1";
        if(classSettlement.getUserId()!= null) {
            userLevel   = classSettlementService.isStaffBGApi(classSettlement.getUserId());
        }
        ResultData resultData = null;
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        Map<String, Object> resultMap = new HashMap<String, Object>();
        List<Map<String, Object>> resultMapList = new ArrayList<Map<String, Object>>();
        List<ClassSettlement> classSettlements = new ArrayList<ClassSettlement>();
        if (classSettlement.getStationId() == null) {
            resultData = ResultData.error(CodeMsg.REQUEST_FAIL);
            return gson.toJson(resultData);
        }



        classSettlement=   payOrderService.classSettlementtimeSetting(classSettlement,classSettlement.getStationId().intValue());

        List<ClassSettlement> classSettlementList = new ArrayList<>();
        if(userLevel.equals("3")||userLevel.equals("2")){
            classSettlement.setCreateUser(classSettlement.getUserId());
            classSettlementList = classSettlementService.selectClassSettlementStaffSummaryList(classSettlement);
        }else{
            classSettlementList = classSettlementService.selectClassSettlementSummaryList(classSettlement);
        }

        if (classSettlementList == null || classSettlementList.size() == 0) {
            resultData = ResultData.success(null);
            return gson.toJson(resultData);
        }
        List<String> classNoList = new ArrayList<String>();
        for (ClassSettlement settlement : classSettlementList) {
            classNoList.add(settlement.getClassNo());
        }
        Map<String, Object> queryMap = new HashMap<String, Object>();
        queryMap.put("stationId", classSettlement.getStationId());
        queryMap.put("classNoList", classNoList);
        List<ClassSettlement> listDetail = classSettlementService.selectClassSettlementSummary4POSList(queryMap);
        String userName = "";
        List<ClassSettlement> detailList = new ArrayList<ClassSettlement>();
        List<Map<String, Object>> userDetail = new ArrayList<Map<String, Object>>();

        for (ClassSettlement settlement : classSettlementList) {
            resultMap = new HashMap<String, Object>();
            List<ClassSettlement> classSettlementSubList = new ArrayList<ClassSettlement>();
            for (ClassSettlement settlementDetail : listDetail) {
                if (settlement.getClassNo().equals(settlementDetail.getClassNo())) {
                    classSettlementSubList.add(settlementDetail);
                }
            }
            resultMap.put("summary", settlement);
            resultMap.put("details", classSettlementSubList);
            resultMapList.add(resultMap);
        }
        resultData = ResultData.success(resultMapList);
        return gson.toJson(resultData);
    }

    /**
     * POS查询班结列表或者详情
     */
    @ApiOperation(value = "POS查询班结列表或者详情", httpMethod = "POST", notes = "POS查询班结列表或者详情")
    @PostMapping(value = "/detail4pos", produces = "application/json;charset=UTF-8")
    @Transactional
    public String detail4pos(@RequestBody ClassSettlement classSettlement) {

        ResultData resultData = null;
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        Map<String, Object> resultMap = new HashMap<String, Object>();
        List<Map<String, Object>> resultMapList = new ArrayList<Map<String, Object>>();
        List<ClassSettlement> classSettlements = new ArrayList<ClassSettlement>();
        if (classSettlement.getClassNo() == null) {
            resultData = ResultData.error(CodeMsg.REQUEST_FAIL);
            return gson.toJson(resultData);
        }
        List<ClassSettlement> classSettlementList = classSettlementService.selectClassSettlementSummaryList(classSettlement);
        if (classSettlementList == null || classSettlementList.size() == 0) {
            resultData = ResultData.success(null);
            return gson.toJson(resultData);
        }
        List<String> classNoList = new ArrayList<String>();
        for (ClassSettlement settlement : classSettlementList) {
            classNoList.add(settlement.getClassNo());
        }
        Map<String, Object> queryMap = new HashMap<String, Object>();
        queryMap.put("stationId", classSettlement.getStationId());
        queryMap.put("classNoList", classNoList);
        List<ClassSettlement> listDetail = classSettlementService.selectClassSettlementSummary4POSList(queryMap);
        List<ClassSettlement> listDetail4User = classSettlementService.selectClassSettlement4User4POSList(queryMap);
        Map<String, Object> summaryMap = new HashMap<String, Object>();
        Long orderCount = 0L;//订单笔数
        BigDecimal amt = BigDecimal.ZERO;//实收金额
        BigDecimal receivableAmt = BigDecimal.ZERO;//应收金额
        BigDecimal discountAmt = BigDecimal.ZERO;//优惠金额
        BigDecimal orderLiters = BigDecimal.ZERO;//加油升数
        BigDecimal moreAmt = BigDecimal.ZERO;//短款金额
        BigDecimal refundAmt = BigDecimal.ZERO;//退款金额

        for (ClassSettlement settlement : classSettlementList) {
            //详情，只有一条
            resultMap = new HashMap<String, Object>();
            List<ClassSettlement> classSettlementSubList = new ArrayList<ClassSettlement>();
            for (ClassSettlement settlementDetail : listDetail) {
                if (settlement.getClassNo().equals(settlementDetail.getClassNo())) {
                    classSettlementSubList.add(settlementDetail);
                }
            }
            orderCount = MathUtil.add(orderCount ,settlement.getOrderCount());
            amt = MathUtil.add(amt,settlement.getAmt());
            receivableAmt = MathUtil.add(receivableAmt,settlement.getReceivableAmt());
            discountAmt = MathUtil.add(discountAmt,settlement.getDiscountAmt());
            orderLiters = MathUtil.add(orderLiters,settlement.getOrderLiters());
            moreAmt = MathUtil.add(moreAmt,settlement.getMoreAmt());
            refundAmt = MathUtil.add(refundAmt,settlement.getRefundAmt());

            summaryMap.put("orderCount", orderCount);
            summaryMap.put("amt", amt);
            summaryMap.put("receivableAmt", receivableAmt);
            summaryMap.put("discountAmt", discountAmt);
            summaryMap.put("orderLiters", orderLiters);
            summaryMap.put("moreAmt", moreAmt);
            summaryMap.put("refundAmt", refundAmt);
            resultMap.put("summary", summaryMap);
            resultMap.put("details", classSettlementSubList);
            String userName = "";
            List<ClassSettlement> detailList = new ArrayList<ClassSettlement>();
            List<Map<String, Object>> userDetail = new ArrayList<Map<String, Object>>();
            orderLiters = BigDecimal.ZERO;
            amt = BigDecimal.ZERO;
            refundAmt = BigDecimal.ZERO;
            orderCount = 0L;
            for (ClassSettlement settlement4User : listDetail4User) {
                if (!StringUtils.equals(settlement4User.getOilPersonnelName(),userName)) {
                    if (!userName.equals("")) {
                        Map<String, Object> map = new HashMap<String, Object>();
                        ClassSettlement hz = new ClassSettlement();
                        hz.setOilName("合计");
                        hz.setOrderCount(orderCount);
                        hz.setAmt(amt);
                        hz.setOrderLiters(orderLiters);
                        detailList.add(hz);
                        map.put("userName", userName);
                        map.put("detailList", detailList);
                        userDetail.add(map);
                    }
                    userName = settlement4User.getOilPersonnelName();
                    //新的加油员，
                    detailList = new ArrayList<ClassSettlement>();
                    orderLiters = BigDecimal.ZERO;
                    amt = BigDecimal.ZERO;
                    orderCount = 0L;
                }
                amt = MathUtil.add(amt,settlement4User.getAmt());
                refundAmt = MathUtil.add(refundAmt,settlement4User.getRefundAmt());
                orderLiters = MathUtil.add(orderLiters,settlement4User.getOrderLiters());
                orderCount = MathUtil.add(orderCount,settlement4User.getOrderCount());
                detailList.add(settlement4User);
            }
            Map<String, Object> map = new HashMap<String, Object>();
            ClassSettlement hz = new ClassSettlement();
            hz.setOilName("合计");
            hz.setOrderCount(orderCount);
            hz.setAmt(amt);
            hz.setRefundAmt(refundAmt);
            hz.setOrderLiters(orderLiters);
            detailList.add(hz);
            map.put("userName", userName);
            map.put("detailList", detailList);
            userDetail.add(map);
            resultMap.put("details4User", userDetail);
            resultMapList.add(resultMap);
            resultData = ResultData.success(resultMap);
            return gson.toJson(resultData);
        }
        return null;
    }

    /**
     * 班结
     */
    @ApiOperation(value = "班结", httpMethod = "POST", notes = "班结")
    @PostMapping(value = "/createClassSe", produces = "application/json;charset=UTF-8")
    @Transactional
    public String createClassSe(@RequestBody ClassSettlement classSettlement) {
        classSettlement.setEquipmentCode("pos机");
        ResultData resultData = null;
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        Map<String, Object> resultMap = new HashMap<String, Object>();
        List<Map<String, Object>> resultMapList = new ArrayList<Map<String, Object>>();
        logger.info("createClassSe-params============================" + JSON.toJSONString(classSettlement));
        if (classSettlement.getClassEndTime() == null || classSettlement.getStationId() == null || classSettlement.getEquipmentCode() == null
                || classSettlement.getCreateUser() == null) {
            resultData = ResultData.error(CodeMsg.REQUEST_FAIL);
            return gson.toJson(resultData);
        }
        Station station = enterpriseService.selectStationById(Math.toIntExact(classSettlement.getStationId()));
        //判断油站是否开启自动班结
        if (station.getIsAutomaticClass() == 1){
            resultData = ResultData.error(CodeMsg.ENABLE_AUTOMATIC_SCHEDULING);
            return gson.toJson(resultData);
        }
        SysUser user = posMachineService.selectUserByUserId(classSettlement.getCreateUser().toString());
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat simFmtBef = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat simFmtAft = new SimpleDateFormat("HHmm");
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("stationId", classSettlement.getStationId());
        Map<String, Object> endTimeMap = classSettlementService.queryLastEndTime(params);

        params.clear();
        params.put("serviceType", "BGS");//班结的时候多维度分组查询
        String startTime = null;
        if (endTimeMap != null && endTimeMap.containsKey("classEndTime") && endTimeMap.get("classEndTime") != null) {
//            params.put("createStartTime","2021-07-10 00:00:00");
            startTime = endTimeMap.get("classEndTime").toString();
        }
        params.put("createStartTime", startTime);
        params.put("createEndTime", fmt.format(classSettlement.getClassEndTime()));
        params.put("stationId", classSettlement.getStationId());
        String classesDayOrNight = classSettlementService.queryClassDayOrNight(classSettlement.getStationId(),classSettlement.getClassEndTime());
        List<ClassSettlement> classSettlements = classSettlementService.queryUntreatedData(params);
        List<ClassSettlement> classSettlementPayWay = classSettlementService.queryPayWayData(params);
        //List<ClassSettlementCard> classSettlementCardsSum = classSettlementCardService.queryUntreatedDataSum(params);
        List<ClassSettlementCard> classSettlementCards = classSettlementCardService.queryUntreatedData(params);
        // 调用方法获取总金额
        //BigDecimal actualRechargeReceivedAmt =  classSettlementService.getTotalAmtByConditions(params);
        //电子卡赠送金额
        //BigDecimal actualRechargeGiftAmt = classSettlementService.getTotalPresentAmtByConditions(params);

        CardClassSettDto settDto = countCardSett(classSettlementCards);
        BigDecimal killCouponAmt = classSettlementService.forKillCouponAmt(params) ;
        ClassSettlement superPay = classSettlementService.querySuperPay(params) ;
//                优惠券核销，然后把核销的金额统计起来，放进优惠券金额汇总里面
        BigDecimal actualRechargeReceivedAmt = classSettlementService.forActualRechargeReceivedAmt(settDto.getTotalAmt(),params) ;
        BigDecimal actualRechargeGiftAmt = settDto.getTotalGiveAmt();
        BigDecimal totalRechargeWithdrawalAmount = settDto.getTotalWithdrawalAmount();
        BigDecimal totalRechargeRefundAmt = settDto.getTotalRefundAmt();
        BigDecimal superPayAmt = superPay.getTotalWithdrawalAmount();
        Long stationId = (Long) params.get("stationId");
        Station userstation = enterpriseService.selectStationById(stationId.intValue());
// 将 double 值转换为 BigDecimal



        if (classSettlementPayWay != null && classSettlementPayWay.size() > 0) {
            for (ClassSettlement classSettlement1 : classSettlementPayWay) {
                PayWay payWay = new PayWay();
                payWay.setPayWayId(Integer.parseInt(classSettlement1.getPayWayId() + ""));
                List<PayWay> payWays = enterpriseService.selectStaPayWay(payWay);
                try {
                    TLFusClassPayUtil.tLClassSettle(classSettlement1, payWays.get(0));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        Map<String, Object> summaryMap = new HashMap<String, Object>();
        Long orderCount = 0L;//订单笔数
        BigDecimal amt = BigDecimal.ZERO;//实收金额
        BigDecimal refundAmt = BigDecimal.ZERO;//退款金额
        BigDecimal discountCoponAmt = BigDecimal.ZERO;//退款金额
        BigDecimal receivableAmt = BigDecimal.ZERO;//应收金额
        BigDecimal discountAmt = BigDecimal.ZERO;//优惠金额
        BigDecimal orderLiters = BigDecimal.ZERO;//加油升数
        BigDecimal moreAmt = BigDecimal.ZERO;//短款金额
        String no = simFmtBef.format(classSettlement.getClassEndTime()) + classSettlement.getStationId() + simFmtAft.format(classSettlement.getClassEndTime());
        classSettlementService.insertAboutOil(params,no,fmt.format(classSettlement.getClassEndTime()),classSettlement.getStationId());
        params.put("no",no);
        classSettlementService.selectChange4User4POSListForOrder(params);

        //        充值合计金额
        List<ClassSettlementOilmachine> classSettlementOilmachines = classSettlement.getClassSettlementOilmachines();
        if (classSettlementOilmachines != null && !classSettlementOilmachines.isEmpty()) {
            for (ClassSettlementOilmachine oilmachine : classSettlementOilmachines) {
                // 设置缺少的字段
                oilmachine.setStationId(classSettlement.getStationId().intValue());
                oilmachine.setStationName(userstation.getStationName());
                try {
                    if (startTime != null) {
                        oilmachine.setClassStartTime(fmt.parse(startTime));
                    }
                    oilmachine.setClassEndTime(classSettlement.getClassEndTime());
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                oilmachine.setClassNo(no);
                classSettlementService.insertClassSettlementOilmachine(oilmachine);
            }
        }
        if (actualRechargeReceivedAmt!=null && actualRechargeReceivedAmt.compareTo(BigDecimal.ZERO) != 0||
                actualRechargeGiftAmt!=null && actualRechargeGiftAmt.compareTo(BigDecimal.ZERO) != 0||
                totalRechargeWithdrawalAmount!=null && totalRechargeWithdrawalAmount.compareTo(BigDecimal.ZERO) != 0||
                totalRechargeRefundAmt!=null && totalRechargeRefundAmt.compareTo(BigDecimal.ZERO) != 0||
                killCouponAmt!=null && killCouponAmt.compareTo(BigDecimal.ZERO) != 0||
                superPayAmt!=null && superPayAmt.compareTo(BigDecimal.ZERO) != 0) {
            ClassSettlement settlementonlyactualRechargeReceivedAmt = new ClassSettlement();
            settlementonlyactualRechargeReceivedAmt.setKillCouponAmt(killCouponAmt);
            settlementonlyactualRechargeReceivedAmt.setActualRechargeReceivedAmt(actualRechargeReceivedAmt);
            settlementonlyactualRechargeReceivedAmt.setActualRechargeGiftAmt(actualRechargeGiftAmt);
            settlementonlyactualRechargeReceivedAmt.setTotalWithdrawalAmount(totalRechargeWithdrawalAmount);
            settlementonlyactualRechargeReceivedAmt.setRefundAmt(totalRechargeRefundAmt);
            settlementonlyactualRechargeReceivedAmt.setClassNo(no);
            settlementonlyactualRechargeReceivedAmt.setClassesDayOrNight(classesDayOrNight);
            settlementonlyactualRechargeReceivedAmt.setCreateUser(Long.valueOf(user.getUserId()));
            settlementonlyactualRechargeReceivedAmt.setEquipmentCode("PC");
            settlementonlyactualRechargeReceivedAmt.setStationId((Long) stationId);
            settlementonlyactualRechargeReceivedAmt.setSuperPayAmt(superPayAmt);
            settlementonlyactualRechargeReceivedAmt.setStationName(userstation.getStationName());
            settlementonlyactualRechargeReceivedAmt.setCreateName(user.getUserName());
            try {
                if (startTime != null) {
                    settlementonlyactualRechargeReceivedAmt.setClassStartTime(fmt.parse(startTime));
                }
                settlementonlyactualRechargeReceivedAmt.setClassEndTime(classSettlement.getClassEndTime());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            settlementonlyactualRechargeReceivedAmt.setNote(classSettlement.getNote());
            classSettlementService.insertClassSettlement(settlementonlyactualRechargeReceivedAmt);
        }
        for (ClassSettlement settlement : classSettlements) {
            settlement.setCreateName(user.getUserName());
            settlement.setCreateUser(Long.valueOf(user.getUserId()));
            settlement.setEquipmentCode(classSettlement.getEquipmentCode());
            //设置通联支付的时候的班结号码
            settlement.setNewClassNo(no);
            settlement.setClassesDayOrNight(classesDayOrNight);
            try {
                if (startTime != null) {
                    settlement.setClassStartTime(fmt.parse(startTime));
                }
                settlement.setClassEndTime(classSettlement.getClassEndTime());
            } catch (ParseException e) {
                e.printStackTrace();
            }
//            settlement.setEnterpriseId(Long.valueOf(user.getEnterpriseId()));
            settlement.setNote(classSettlement.getNote());
            settlement.setClassNo(no);
            classSettlementService.insertClassSettlement(settlement);
        }
        ClassSettlementCard wxClassSett = null;

        List<ClassSettlementCard> cardSe = settDto.getSettlementCardList();
        for (ClassSettlementCard card : cardSe) {
            if (StringUtils.equals(CardRecordType.WX_RECHARGE.getKey(),card.getPayType())) {
                wxClassSett = card;
                break;
            }
        }
        for (ClassSettlementCard settlement : classSettlementCards) {
            settlement.setCreateName(user.getUserName());
            settlement.setCreateUser(Long.valueOf(user.getUserId()));
            settlement.setEquipmentCode(classSettlement.getEquipmentCode());
            settlement.setCreateTime(new Date());
            try {
                if (startTime != null) {
                    settlement.setClassStartTime(fmt.parse(startTime));
                }
                settlement.setClassEndTime(classSettlement.getClassEndTime());
            } catch (ParseException e) {
                e.printStackTrace();
            }
//            settlement.setEnterpriseId(Long.valueOf(user.getEnterpriseId()));
            settlement.setNote(classSettlement.getNote());
            settlement.setClassNo(no);
            classSettlementCardService.insertClassSettlementCard(settlement);
        }
        BigDecimal czSum = BigDecimal.ZERO;
        BigDecimal serviceChargeSum = BigDecimal.ZERO;
//        for (ClassSettlementCard classSettlementCard : classSettlementCardsSum) {
//            if (classSettlementCard.getAmt() != null) {
//                czSum = czSum.add(classSettlementCard.getAmt());
//                if (classSettlementCard.getServiceCharge() != null) {
//                    serviceChargeSum = serviceChargeSum.add(classSettlementCard.getServiceCharge());
//                }
//            }
//        }
//        班结数为零的时候
        if (classSettlements.size() == 0) {
            ClassSettlement settlement = new ClassSettlement();
            settlement.setCreateName(user.getUserName());
            settlement.setCreateUser(Long.valueOf(user.getUserId()));
            settlement.setClassNo(no);
            settlement.setClassesDayOrNight(classesDayOrNight);
            settlement.setStationId((Long) stationId);
            settlement.setStationName(userstation.getStationName());
            try {
                if (startTime != null) {
                    settlement.setClassStartTime(fmt.parse(startTime));
                }
                settlement.setClassEndTime(classSettlement.getClassEndTime());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            settlement.setNote(classSettlement.getNote());
            classSettlementService.insertClassSettlement(settlement);
        }
        //班结成功，返回打印小票需要的数据
//        Long stationId = classSettlement.getStationId();
        classSettlement = new ClassSettlement();
        classSettlement.setStationId(stationId);
        classSettlement.setClassNo(no);
        List<ClassSettlement> classSettlementList = classSettlementService.selectClassSettlementSummaryList(classSettlement);
        if (classSettlementList == null || classSettlementList.size() == 0) {
            resultData = ResultData.success(null);
            return gson.toJson(resultData);
        }
        List<String> classNoList = new ArrayList<String>();
        for (ClassSettlement settlement : classSettlementList) {
            classNoList.add(settlement.getClassNo());
        }
        Map<String, Object> queryMap = new HashMap<String, Object>();
        queryMap.put("stationId", classSettlement.getStationId());
        queryMap.put("classNoList", classNoList);
        List<ClassSettlement> listDetail = classSettlementService.selectClassSettlementSummary4POSList(queryMap);
        List<ClassSettlement> listDetail4User = classSettlementService.selectClassSettlement4User4POSList(queryMap);
        for (ClassSettlement settlement : classSettlementList) {
            resultMap = new HashMap<String, Object>();
            List<ClassSettlement> classSettlementSubList = new ArrayList<ClassSettlement>();
            ClassSettlement detailCount = new ClassSettlement();
            detailCount.setOilName("合计");
            classSettlementSubList.add(detailCount);
            for (ClassSettlement settlementDetail : listDetail) {
                if (StringUtils.isNotBlank(settlementDetail.getOilName()) && StringUtils.equals(settlement.getClassNo(),settlementDetail.getClassNo())) {
                    classSettlementSubList.add(settlementDetail);
                    detailCount.setOrderCount(MathUtil.add(detailCount.getOrderCount(),settlementDetail.getOrderCount()));
                    detailCount.setAmt(MathUtil.add(detailCount.getAmt(),settlementDetail.getAmt()));
                    detailCount.setOrderLiters(MathUtil.add(detailCount.getOrderLiters(),settlementDetail.getOrderLiters()));
                }
            }
//            settlement.setCollectionAmt(settlement.getAmt());
            settlement.setDiscountAmt(MathUtil.add(settlement.getDiscountAmt(),settlement.getDiscountCouponAmt()));
            resultMap.put("summary", settlement);
            resultMap.put("details", classSettlementSubList);

            queryMap.clear();
            queryMap.put("classNo", no);
            List<Map<String, Object>> maps = classSettlementService.queryGroupByPayType(queryMap);
            for (Iterator<Map<String, Object>> iterator = maps.iterator(); iterator.hasNext(); ) {
                Map<String, Object> map = iterator.next();
                String type = (String) map.get("pay_type");
                if (StringUtils.isBlank(type)) {
                    iterator.remove();
                    continue;
                }
                map.put("pay_type", PayTypeEnum.getByType(type).getDes());
            }
            resultMap.put("detailsForPayType", maps);

            String userName = "";
            List<ClassSettlement> detailList = new ArrayList<ClassSettlement>();
            List<Map<String, Object>> userDetail = new ArrayList<Map<String, Object>>();
            orderLiters = BigDecimal.ZERO;
            amt = BigDecimal.ZERO;
            refundAmt = BigDecimal.ZERO;
            orderCount = 0L;
            for (ClassSettlement settlement4User : listDetail4User) {
                if (!settlement4User.getOilPersonnelName().equals(userName)) {
                    if (!userName.equals("")) {
                        Map<String, Object> map = new HashMap<String, Object>();
                        ClassSettlement hz = new ClassSettlement();
                        hz.setOilName("合计");
                        hz.setOrderCount(orderCount);
                        hz.setAmt(amt);
                        hz.setRefundAmt(refundAmt);
                        hz.setOrderLiters(orderLiters);
                        detailList.add(hz);
                        map.put("userName", userName);
                        map.put("detailList", detailList);
                        userDetail.add(map);
                    }
                    userName = settlement4User.getOilPersonnelName();
                    //新的加油员，
                    detailList = new ArrayList<ClassSettlement>();
                    orderLiters = BigDecimal.ZERO;
                    amt = BigDecimal.ZERO;
                    refundAmt = BigDecimal.ZERO;
                    orderCount = 0L;
                    discountCoponAmt = BigDecimal.ZERO;
                }
                ;
                if (settlement4User.getAmt() != null) {
                    amt = amt.add(settlement4User.getAmt());
                }
                if (settlement4User.getRefundAmt() != null) {
                    refundAmt = refundAmt.add(settlement4User.getRefundAmt());
                }
                if (settlement4User.getOrderLiters() != null) {
                    orderLiters = orderLiters.add(settlement4User.getOrderLiters());
                }
                if (settlement4User.getOrderCount() != null) {
                    orderCount += settlement4User.getOrderCount();
                }
                if (settlement4User.getDiscountCouponAmt() != null) {
                    discountCoponAmt = discountCoponAmt.add(settlement4User.getDiscountCouponAmt());
                }
                detailList.add(settlement4User);
            }
            Map<String, Object> map = new HashMap<String, Object>();
            ClassSettlement hz = new ClassSettlement();
            hz.setOilName("合计");
            hz.setOrderCount(orderCount);
            hz.setAmt(amt);
            hz.setRefundAmt(refundAmt);
            hz.setOrderLiters(orderLiters);
            hz.setDiscountCouponAmt(discountCoponAmt);
            detailList.add(hz);
            map.put("userName", userName);
            map.put("detailList", detailList);
            userDetail.add(map);
            resultMap.put("details4User", userDetail);
            resultMap.put("classSettlementCards", wxClassSett == null ? Collections.emptyList() : Collections.singletonList(wxClassSett));
            resultMap.put("czSum", czSum);
            resultMap.put("serviceChargeSum", serviceChargeSum);
            resultMap.put("discountCoponAmt", discountCoponAmt);
            resultMap.put("classPersonFlag", station.getClassPersonFlag());
            resultMap.put("startTime", startTime == null ? "首次" : startTime);
            resultMapList.add(resultMap);
        }

        logger.info("createClassSe-back============================" + JSON.toJSONString(resultMap));
        resultData = ResultData.success(resultMap);
        return gson.toJson(resultData);
    }

    private CardClassSettDto countCardSett(List<ClassSettlementCard> settlementCardList){
        Map<CardRecordType,ClassSettlementCard> map = new HashMap<>();
        // 根据payType进行分组统计
        for (ClassSettlementCard settlementCard : settlementCardList) {
            if (!StringUtils.equals("dzk",settlementCard.getRechargeType())) {
                continue;
            }
            CardRecordType payType = CardRecordType.getByKey(settlementCard.getPayType(),CardRecordType.CONSUME);
            ClassSettlementCard settlement = map.get(payType);
            if (settlement == null) {
                settlement = new ClassSettlementCard();
                settlement.setPayType(payType.getKey());
                settlement.setAmt(BigDecimal.ZERO);
                settlement.setOrderCount(0L);
                settlement.setServiceCharge(BigDecimal.ZERO);
                settlement.setGiveAmt(BigDecimal.ZERO);
                map.put(payType,settlement);
            }
            settlement.setAmt(MathUtil.add(settlement.getAmt(),settlementCard.getAmt()));
            settlement.setOrderCount(MathUtil.add(settlement.getOrderCount(),settlementCard.getOrderCount()));
            settlement.setServiceCharge(MathUtil.add(settlement.getServiceCharge(),settlementCard.getServiceCharge().setScale(2, RoundingMode.HALF_UP)));
            settlement.setGiveAmt(MathUtil.add(settlement.getGiveAmt(),settlementCard.getGiveAmt()));
        }
        CardClassSettDto settDto = new CardClassSettDto();// 每个payType数据相加的总计
        settDto.setTotalAmt(BigDecimal.ZERO);
        settDto.setTotalRechargeAmt(BigDecimal.ZERO);
        settDto.setTotalGiveAmt(BigDecimal.ZERO);
        settDto.setTotalWithdrawalAmount(BigDecimal.ZERO);
        settDto.setTotalRefundAmt(BigDecimal.ZERO);
        settDto.setTotalServiceCharge(BigDecimal.ZERO);
        ArrayList<ClassSettlementCard> settList = new ArrayList<>(); // 包含所有payType数据的列表
        // 遍历所有的payType,添加map中没有的类型，并进行总计
        for (CardRecordType value : CardRecordType.values()) {
            ClassSettlementCard settlement = map.get(value);
            if (settlement == null) {
                settlement = new ClassSettlementCard();
                settlement.setPayType(value.getKey());
                settlement.setAmt(BigDecimal.ZERO);
                settlement.setOrderCount(0L);
                settlement.setServiceCharge(BigDecimal.ZERO);
                settlement.setGiveAmt(BigDecimal.ZERO);
                settlement.setWithdrawalAmount(BigDecimal.ZERO);
            }
            settList.add(settlement);
            settDto.setTotalOrderCount((int) (settDto.getTotalOrderCount()+ settlement.getOrderCount()));
            switch (value){
//                case MANUAL_ADD:
//                    settDto.setTotalAmt(settDto.getTotalAmt().add(settlement.getAmt()));
//                    break;
//                case MANUAL_SUB:
//                    settlement.setAmt(settlement.getAmt().negate());
//                    settDto.setTotalAmt(settDto.getTotalAmt().add(settlement.getAmt()));
//                    break;
                case POS_RECHARGE:
                case WX_RECHARGE:
                    settDto.setTotalAmt(settDto.getTotalAmt().add(settlement.getAmt()));
                    settDto.setTotalGiveAmt(settDto.getTotalGiveAmt().add(settlement.getGiveAmt()));
                    settlement.setWithdrawalAmount(settlement.getAmt().subtract(settlement.getServiceCharge())); // 充值提现=实收-渠道费
                    settDto.setTotalWithdrawalAmount(settDto.getTotalWithdrawalAmount().add(settlement.getWithdrawalAmount()));
                    settDto.setTotalRechargeAmt(settDto.getTotalRechargeAmt().add(settlement.getAmt()));
                    settDto.setTotalServiceCharge(settDto.getTotalServiceCharge().add(settlement.getServiceCharge()));
                    settDto.setAmt(settlement.getAmt());
                    settDto.setOrderCount(settlement.getOrderCount());
                    break;
//                case CONSUME:
//                    settlement.setAmt(settlement.getAmt().negate());
//                    settDto.setTotalAmt(settDto.getTotalAmt().add(settlement.getAmt()));
//                    break;
                case REFUND:
                    settDto.setTotalAmt(settDto.getTotalAmt().subtract(settlement.getAmt()));
                    settDto.setTotalRefundAmt(settDto.getTotalRefundAmt().add(settlement.getAmt()));
                    settDto.setTotalGiveAmt(MathUtil.subtract(settDto.getTotalGiveAmt(),settlement.getGiveAmt()));
                    settlement.setWithdrawalAmount(settlement.getServiceCharge().subtract(settlement.getAmt())); // 退款提现=-(实收-渠道费)，总提现要加上这个值
                    settDto.setTotalWithdrawalAmount(settDto.getTotalWithdrawalAmount().add(settlement.getWithdrawalAmount()));
                    settDto.setTotalServiceCharge(MathUtil.subtract(settDto.getTotalServiceCharge(),settlement.getServiceCharge()));
                    //settlement.setAmt(settlement.getAmt().negate());
                    break;
            }
        }
        ClassSettlementCard wxRefund = newEmptyInstant(CardRecordType.WX_REFUND.getKey());
        ClassSettlementCard posRefund = newEmptyInstant(CardRecordType.POS_REFUND.getKey());
        if (!settlementCardList.isEmpty()) {
            ClassSettlementCard one = settlementCardList.get(0);
            Date startTime = one.getClassStartTime();
            Date endTime = one.getClassEndTime();
            Long stationId = one.getStationId();
            if (stationId != null && endTime != null) {
                List<ClassSettlementCard> refundList = classSettlementCardService.sumDzkRechargeRefund(stationId, startTime, endTime);
                for (ClassSettlementCard card : refundList) {
                    if (StringUtils.equals(card.getPayType(), CardRecordType.WX_RECHARGE.getKey())) {
                        wxRefund = card;
                        wxRefund.setPayType(CardRecordType.WX_REFUND.getKey());
                    }else if (StringUtils.equals(card.getPayType(), CardRecordType.POS_RECHARGE.getKey())) {
                        posRefund = card;
                        posRefund.setPayType(CardRecordType.POS_REFUND.getKey());
                    }
                }
            }
        }
        settList.add(wxRefund);
        settList.add(posRefund);
        settDto.setSettlementCardList(settList);
        return settDto;
    }

    private ClassSettlementCard newEmptyInstant(String payType){
        ClassSettlementCard settlementCard = new ClassSettlementCard();
        settlementCard.setPayType(payType);
        settlementCard.setAmt(BigDecimal.ZERO);
        settlementCard.setGiveAmt(BigDecimal.ZERO);
        settlementCard.setServiceCharge(BigDecimal.ZERO);
        settlementCard.setOrderCount(0L);
        return settlementCard;
    }

    /**
     * 班结
     */
    @ApiOperation(value = "补打班结", httpMethod = "POST", notes = "班结")
    @PostMapping(value = "/exportClassSe", produces = "application/json;charset=UTF-8")
    @Transactional
    public String exportClassSe(@RequestBody ClassSettlement classSettlement) {
        ResultData resultData = null;
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        Map<String, Object> resultMap = new HashMap<String, Object>();
        List<Map<String, Object>> resultMapList = new ArrayList<Map<String, Object>>();
        logger.info("createClassSe-params============================" + JSON.toJSONString(classSettlement));
//        if(classSettlement.getClassEndTime() == null || classSettlement.getStationId() == null || classSettlement.getEquipmentCode() == null
//                || classSettlement.getCreateUser() == null){
//            resultData= ResultData.error(CodeMsg.REQUEST_FAIL);
//            return gson.toJson(resultData);
//        }
//        SysUser user = posMachineService.selectUserByUserId(classSettlement.getCreateUser().toString());
//        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        SimpleDateFormat simFmtBef = new SimpleDateFormat("yyyyMMdd");
//        SimpleDateFormat simFmtAft = new SimpleDateFormat("HHmm");
//        Map<String,Object> params = new HashMap<String,Object>();
//        params.put("stationId",classSettlement.getStationId());
//        Map<String, Object> endTimeMap = classSettlementService.queryLastEndTime(params);
//
//        params.clear();
//        params.put("serviceType","BGS");//班结的时候多维度分组查询
        String startTime = null;
//        if(endTimeMap != null && endTimeMap.containsKey("classEndTime") && endTimeMap.get("classEndTime") != null){
////            params.put("createStartTime","2021-07-10 00:00:00");
//            startTime = endTimeMap.get("classEndTime").toString();
//        }
//        params.put("createStartTime",startTime);
//        params.put("createEndTime",fmt.format(classSettlement.getClassEndTime()));
//        params.put("stationId",classSettlement.getStationId());
//        List<ClassSettlement> classSettlements = classSettlementService.queryUntreatedData(params);
//        List<ClassSettlement> classSettlementPayWay=classSettlementService.queryPayWayData(params);
//        List<ClassSettlementCard> classSettlementCardsSum = classSettlementCardService.queryUntreatedDataSum(params);
//        List<ClassSettlementCard> classSettlementCards = classSettlementCardService.queryUntreatedData(params);
//        if(classSettlementPayWay!=null&&classSettlementPayWay.size()>0){
//            for(ClassSettlement classSettlement1:classSettlementPayWay){
//                PayWay payWay=new PayWay();
//                payWay.setPayWayId(Integer.parseInt(classSettlement1.getPayWayId()+""));
//                List<PayWay> payWays=enterpriseService.selectStaPayWay(payWay);
//                try {
//                    TLFusClassPayUtil.tLClassSettle(classSettlement1, payWays.get(0));
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//        Map<String,Object> summaryMap = new HashMap<String,Object>();
        ClassSettlementCard classSettlementCard1 = new ClassSettlementCard();
        classSettlementCard1.setClassNo(classSettlement.getClassNo());
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<ClassSettlementCard> classSettlementCardsSum = classSettlementCardService.queryGroupByCardType(classSettlementCard1);


        Long orderCount = 0L;//订单笔数
        BigDecimal amt = BigDecimal.ZERO;//实收金额
        BigDecimal refundAmt = BigDecimal.ZERO;//退款金额
        BigDecimal discountCoponAmt = BigDecimal.ZERO;//退款金额
        BigDecimal receivableAmt = BigDecimal.ZERO;//应收金额
        BigDecimal discountAmt = BigDecimal.ZERO;//优惠金额
        BigDecimal orderLiters = BigDecimal.ZERO;//加油升数
        BigDecimal moreAmt = BigDecimal.ZERO;//短款金额
//        String no = simFmtBef.format(classSettlement.getClassEndTime())+classSettlement.getStationId()+simFmtAft.format(classSettlement.getClassEndTime());
//        for (ClassSettlement settlement : classSettlements) {
//            settlement.setCreateName(user.getUserName());
//            settlement.setCreateUser(Long.valueOf(user.getUserId()));
//            settlement.setEquipmentCode(classSettlement.getEquipmentCode());
//            //设置通联支付的时候的班结号码
//            settlement.setNewClassNo(no);
//            try {
//                if(startTime != null){
//                    settlement.setClassStartTime(fmt.parse(startTime));
//                }
//                settlement.setClassEndTime(classSettlement.getClassEndTime());
//            } catch (ParseException e) {
//                e.printStackTrace();
//            }
////            settlement.setEnterpriseId(Long.valueOf(user.getEnterpriseId()));
//            settlement.setNote(classSettlement.getNote());
//            settlement.setClassNo(no);
//            classSettlementService.insertClassSettlement(settlement);
//        }
//        for (ClassSettlementCard settlement : classSettlementCards) {
//            settlement.setCreateName(user.getUserName());
//            settlement.setCreateUser(Long.valueOf(user.getUserId()));
//            settlement.setEquipmentCode(classSettlement.getEquipmentCode());
//            settlement.setCreateTime(new Date());
//            try {
//                if(startTime != null){
//                    settlement.setClassStartTime(fmt.parse(startTime));
//                }
//                settlement.setClassEndTime(classSettlement.getClassEndTime());
//            } catch (ParseException e) {
//                e.printStackTrace();
//            }
////            settlement.setEnterpriseId(Long.valueOf(user.getEnterpriseId()));
//            settlement.setNote(classSettlement.getNote());
//            settlement.setClassNo(no);
//            classSettlementCardService.insertClassSettlementCard(settlement);
//        }
        BigDecimal czSum = BigDecimal.ZERO;
        BigDecimal serviceChargeSum = BigDecimal.ZERO;
        //班结成功，返回打印小票需要的数据


        List<ClassSettlement> classSettlementList = classSettlementService.selectClassSettlementSummaryList(classSettlement);

        Station station = enterpriseService.selectStationById(Math.toIntExact(classSettlementList.get(0).getStationId()));

        if (classSettlementList == null || classSettlementList.size() == 0) {
            resultData = ResultData.success(null);
            return gson.toJson(resultData);
        }
        List<String> classNoList = new ArrayList<String>();
        for (ClassSettlement settlement : classSettlementList) {
            classNoList.add(settlement.getClassNo());
        }
        Map<String, Object> queryMap = new HashMap<String, Object>();
        queryMap.put("stationId", classSettlement.getStationId());
        queryMap.put("classNoList", classNoList);
        List<ClassSettlement> listDetail = classSettlementService.selectClassSettlementSummary4POSList(queryMap);
        List<ClassSettlement> listDetail4User = classSettlementService.selectClassSettlement4User4POSList(queryMap);
        for (ClassSettlement settlement : classSettlementList) {
            resultMap = new HashMap<String, Object>();
            List<ClassSettlement> classSettlementSubList = new ArrayList<ClassSettlement>();
            ClassSettlement detailCount = new ClassSettlement();
            detailCount.setOilName("合计");
            classSettlementSubList.add(detailCount);
            for (ClassSettlement settlementDetail : listDetail) {
                if (StringUtils.isNotBlank(settlementDetail.getOilName()) && StringUtils.equals(settlement.getClassNo(),settlementDetail.getClassNo())) {
                    classSettlementSubList.add(settlementDetail);
                    detailCount.setOrderCount(MathUtil.add(detailCount.getOrderCount(),settlementDetail.getOrderCount()));
                    detailCount.setAmt(MathUtil.add(detailCount.getAmt(),settlementDetail.getAmt()));
                    detailCount.setOrderLiters(MathUtil.add(detailCount.getOrderLiters(),settlementDetail.getOrderLiters()));
                }
            }
            if (settlement.getClassStartTime() != null) {
                startTime = fmt.format(settlement.getClassStartTime());
            }
//            settlement.setCollectionAmt(settlement.getAmt());
            settlement.setDiscountAmt(MathUtil.add(settlement.getDiscountAmt(),settlement.getDiscountCouponAmt()));
            resultMap.put("summary", settlement);
            resultMap.put("details", classSettlementSubList);

            queryMap.clear();
            queryMap.put("classNo", classSettlement.getClassNo());
            List<Map<String, Object>> maps = classSettlementService.queryGroupByPayType(queryMap);
            for (Iterator<Map<String, Object>> iterator = maps.iterator(); iterator.hasNext(); ) {
                Map<String, Object> map = iterator.next();
                String type = (String) map.get("pay_type");
                if (StringUtils.isBlank(type)) {
                    iterator.remove();
                    continue;
                }
                map.put("pay_type", PayTypeEnum.getByType(type).getDes());
            }
            resultMap.put("detailsForPayType", maps);

            String userName = "";
            List<ClassSettlement> detailList = new ArrayList<ClassSettlement>();
            List<Map<String, Object>> userDetail = new ArrayList<Map<String, Object>>();
            orderLiters = BigDecimal.ZERO;
            amt = BigDecimal.ZERO;
            refundAmt = BigDecimal.ZERO;
            orderCount = 0L;
            for (ClassSettlement settlement4User : listDetail4User) {
                if (!StringUtils.equals(settlement4User.getOilPersonnelName(),userName)) {
                    if (!userName.equals("")) {
                        Map<String, Object> map = new HashMap<String, Object>();
                        ClassSettlement hz = new ClassSettlement();
                        hz.setOilName("合计");
                        hz.setOrderCount(orderCount);
                        hz.setAmt(amt);
                        hz.setRefundAmt(refundAmt);
                        hz.setOrderLiters(orderLiters);
                        detailList.add(hz);
                        map.put("userName", userName);
                        map.put("detailList", detailList);
                        userDetail.add(map);
                    }
                    userName = settlement4User.getOilPersonnelName();
                    //新的加油员，
                    detailList = new ArrayList<ClassSettlement>();
                    orderLiters = BigDecimal.ZERO;
                    amt = BigDecimal.ZERO;
                    refundAmt = BigDecimal.ZERO;
                    orderCount = 0L;
                    discountCoponAmt = BigDecimal.ZERO;
                }

                amt = amt.add(settlement4User.getAmt() == null ? BigDecimal.ZERO : settlement4User.getAmt());
                refundAmt = refundAmt.add(settlement4User.getRefundAmt() == null ? BigDecimal.ZERO : settlement4User.getRefundAmt());
                orderLiters = orderLiters.add(settlement4User.getOrderLiters() == null ? BigDecimal.ZERO : settlement4User.getOrderLiters());
                orderCount = orderCount + (settlement4User.getOrderCount() == null ? 0L : settlement4User.getOrderCount());
                if (settlement4User.getDiscountCouponAmt() != null) {
                    discountCoponAmt = discountCoponAmt.add(settlement4User.getDiscountCouponAmt());
                }
                detailList.add(settlement4User);
            }
            Map<String, Object> map = new HashMap<String, Object>();
            ClassSettlement hz = new ClassSettlement();
            hz.setOilName("合计");
            hz.setOrderCount(orderCount);
            hz.setAmt(amt);
            hz.setRefundAmt(refundAmt);
            hz.setOrderLiters(orderLiters);
            hz.setDiscountCouponAmt(discountCoponAmt);
            detailList.add(hz);
            map.put("userName", userName);
            map.put("detailList", detailList);
            userDetail.add(map);
            resultMap.put("details4User", userDetail);
            resultMap.put("classSettlementCards", classSettlementCardsSum);
            resultMap.put("czSum", czSum);
            resultMap.put("serviceChargeSum", serviceChargeSum);
            resultMap.put("discountCoponAmt", discountCoponAmt);
            resultMap.put("classPersonFlag", station.getClassPersonFlag());
            resultMap.put("startTime", startTime == null ? "首次" : startTime);
            resultMapList.add(resultMap);
        }

        logger.info("createClassSe-back============================" + JSON.toJSONString(resultMap));
        resultData = ResultData.success(resultMap);
        return gson.toJson(resultData);
    }


    /**
     * 班结
     */
    @PostMapping(value = "/tlClass", produces = "application/json;charset=UTF-8")
    @Transactional
    public String tlClass(@RequestBody ClassSettlement classSettlement) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("stationId", classSettlement.getStationId());


        params.clear();
        params.put("serviceType", "BGS");//班结的时候多维度分组查询
        String startTime = null;

        params.put("createStartTime", startTime);
        params.put("createEndTime", classSettlement.getClassEndTime());
        params.put("stationId", classSettlement.getStationId());
        List<ClassSettlement> classSettlementPayWay = classSettlementService.queryPayWayData(params);
        if (classSettlementPayWay != null && classSettlementPayWay.size() > 0) {
            for (ClassSettlement classSettlement1 : classSettlementPayWay) {
                PayWay payWay = new PayWay();
                payWay.setPayWayId(Integer.parseInt(classSettlement1.getPayWayId() + ""));
                List<PayWay> payWays = enterpriseService.selectStaPayWay(payWay);
                try {
                    TLFusClassPayUtil.tLClassSettle(classSettlement1, payWays.get(0));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        return "";
    }

    /**
     * pos机获取班结信息，替换原来的/exportClassSe
     * @date 23-20-9
     * @param classSettlement
     * @return
     */
    @ApiOperation("pos机班结打印")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "classNo", value = "班结号", dataType = "String", paramType = "body"),
    })
    @PostMapping("/classSe/getInfo")
    public String classSePosGetInfo(@RequestBody @ApiParam(hidden = true) ClassSettlement classSettlement){
        return classSettlementService.getPOSClassSettlementInfo(classSettlement);
    }

    /**
     * pos机创建班结并获取班结信息，替换原来的/createClassSe
     * @date 23-20-9
     * @param classSettlement
     * @return
     */
    @ApiOperation("pos机创建班结")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "classEndTime", value = "截止时间,当前时间字符串", dataType = "String", paramType = "body", example = "2023-05-25 18:00:00"),
            @ApiImplicitParam(name = "stationId", value = "油站ID", dataType = "Long", paramType = "body"),
            @ApiImplicitParam(name = "createUser",value = "pos机登录的用户id",dataType = "String", paramType = "body"),
            @ApiImplicitParam(name = "createName",value = "pos机登录的用户名",dataType = "String", paramType = "body"),
            @ApiImplicitParam(name = "equipmentCode",value = "设备，固定写死‘pos机’",dataType = "String", paramType = "body"),
            @ApiImplicitParam(name = "note",value = "班结备注",dataType = "String", paramType = "body")
    })
    @SimpleRepeatedReqLimit(name = "sePosCreate:",express = "[0].getStationId()",condition = "[0] != null && [0].getStationId() != null",expire = 25)
    @PostMapping("/classSe/posCreateAndGet")
    public String createClassSettlement(@RequestBody @ApiParam(hidden = true) ClassSettlement classSettlement) {
        logger.info("createClassSettlement:{}",JSON.toJSONString(classSettlement));
        String classNo = classSettlementService.createClassSettlementBGApi(classSettlement);
        logger.info("createClassSettlementclassNo:{}",classNo);
        if (StringUtils.isBlank(classNo)) {
            throw new CustomException("创建班结失败");
        }
        ClassSettlement se = new ClassSettlement();
        se.setClassNo(classNo);
        se.setStationId(classSettlement.getStationId());
        se.setClassStartTime(classSettlement.getClassStartTime());
        se.setClassEndTime(classSettlement.getClassEndTime());
        return classSettlementService.getPOSClassSettlementInfo(se);
    }


//    @GetMapping("/integral/list")
//    @ResponseBody
//    public BGResult createClassSettlement(CustomerPointsRecordApi customerPointsRecordApi) {
//        BGResult classNo = classSettlementService.customerPointsRecordApi(customerPointsRecordApi);
//
//        return classNo;
//    }

}
